package com.youlai.boot.system.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.annotation.RepeatSubmit;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.system.model.form.SpotRecordForm;
import com.youlai.boot.system.model.form.SpotTicketForm;
import com.youlai.boot.system.model.query.SpotRecordQuery;
import com.youlai.boot.system.model.query.SpotTicketQuery;
import com.youlai.boot.system.model.vo.SpotRecordVO;
import com.youlai.boot.system.model.vo.SpotTicketExcelVO;
import com.youlai.boot.system.model.vo.SpotTicketVO;
import com.youlai.boot.system.service.SpotTicketService;
import com.youlai.boot.util.ExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 预售票数据前端控制层
 *
 * @author 李文兵
 * @since 2025-06-29 17:29
 */
@Tag(name = "预售票数据接口")
@RestController
@RequestMapping("/api/v1/spotTickets")
@RequiredArgsConstructor
public class SpotTicketController {

    private final SpotTicketService spotTicketService;

    //@Operation(summary = "预售票数据分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:query')")
    public PageResult<SpotTicketVO> getSpotTicketPage(SpotTicketQuery queryParams ) {
        IPage<SpotTicketVO> result = spotTicketService.getSpotTicketPage(queryParams);
        return PageResult.success(result);
    }

    //@Operation(summary = "预售票数据统计")
    @GetMapping("/count")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:query')")
    public Result<List<SpotTicketForm>> count(SpotTicketQuery queryParams) {
        return Result.success(spotTicketService.getCount(queryParams));
    }


    @Operation(summary = "导出预售票数据")
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:word')")
    public void export(SpotTicketQuery queryParams, HttpServletResponse response) throws IOException {

        List<SpotTicketExcelVO> list = spotTicketService.export(queryParams);
        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/spotTickets.xlsx");
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(String.format("预售票数据_%s.xlsx", LocalDate.now()), StandardCharsets.UTF_8));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }

    @Operation(summary = "新增预售票数据")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('system:spotTicket:add')")
    @RepeatSubmit(expire = 3)
    @Log(value = "新增预售票数据", module = LogModuleEnum.OTHER)
    public Result<Void> saveSpotTicket(@RequestBody @Valid SpotTicketForm formData ) {
        Long userId = SecurityUtils.getUserId();
        formData.setRecordBy(userId);
        LocalDateTime now = LocalDateTime.now();
        formData.setRecordTime(now);
        boolean result = spotTicketService.saveSpotTicket(formData);
        return Result.judge(result);
    }

    //@Operation(summary = "获取预售票数据表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:edit')")
    public Result<SpotTicketForm> getSpotTicketForm(
        @Parameter(description = "预售票数据ID") @PathVariable Long id
    ) {
        SpotTicketForm formData = spotTicketService.getSpotTicketFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改预售票数据")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:edit')")
    @Log(value = "修改预售票数据", module = LogModuleEnum.OTHER)
    @RepeatSubmit(expire = 3)
    public Result<Void> updateSpotTicket(
            @Parameter(description = "预售票数据ID") @PathVariable Long id,
            @RequestBody @Validated SpotTicketForm formData
    ) {
        boolean result = spotTicketService.updateSpotTicket(id, formData, false);
        return Result.judge(result);
    }

    @Operation(summary = "删除预售票数据")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:delete')")
    @Log(value = "删除预售票数据", module = LogModuleEnum.OTHER)
    public Result<Void> deleteSpotTickets(
        @Parameter(description = "预售票数据ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = spotTicketService.deleteSpotTickets(ids);
        return Result.judge(result);
    }

    @Operation(summary = "发起审核")
    @PostMapping("/report/{ids}")
    @PreAuthorize("@ss.hasPerm('system:spotTicket:report')")
    @Log(value = "发起审核", module = LogModuleEnum.OTHER)
    public Result<Void> reportSpotTickets(
            @Parameter(description = "预售票数据ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = spotTicketService.reportSpotTickets(ids);
        return Result.judge(result);
    }


}
